package mao.exaimnation.vivo;

import java.util.Scanner;

/**
 * @author Totoro
 * @date 2020/9/12
 * @explain:
 */
public class Main1 {
    private static int[][] dir = {{1,0},{-1,0},{0,1},{0,-1}};
    private static int min = Integer.MAX_VALUE;
    private static int cur = 0;
    private static boolean[][] marked;
    static int endY ;
    static int endX ;
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            int n = scanner.nextInt();
            int startX = scanner.nextInt();
            int startY = scanner.nextInt();
            int endX = scanner.nextInt();
            int endY = scanner.nextInt();
            min = Integer.MAX_VALUE;
            cur = 0;
            Main1.endX = endX;
            Main1.endY = endY;

            char[][]  map = new char[n][n];
            marked = new boolean[n][n];
            scanner.nextLine();
            for (int i = 0; i < n; i++) {
                String next = scanner.nextLine();
                map[i] = next.toCharArray();
            }

            dfs(startX,startY,map);

            if (min == Integer.MAX_VALUE){
                System.out.println(-1);
            }else {
                System.out.println(min-1);
            }

        }
    }

    public static void dfs(int startX,int startY,char[][] map){
        if (marked[startX][startY]) return;
        cur++;
        marked[startX][startY] = true;

       if (startX == endX && startY == endY){
           min = Math.min(min,cur);
           return;
       }
        for (int i = 0; i < 4; i++) {
            int newX = startX+dir[i][0];
            int newY = startY+dir[i][1];
            if (newX >=0 && newX<map.length && newY>=0 && newY < map.length){
                if (map[newX][newY] != '#' || map[newX][newY] != '@'){
                    dfs(newX,newY,map);
                }
            }
        }
        cur--;
        marked[startX][startY] = false;
    }
}
